import os
import urllib3
import json
import notify

def login(callback, assets, context):
    http = urllib3.PoolManager()
    url = 'http://testadmin.superant.cc/login/actionlogin'
    headers = urllib3.util.make_headers(keep_alive=True,user_agent='Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6')

    params = {
        'username': 'tcy',
        'pwd': 'tcy123'
    }

    r = http.request('POST', url, params, headers)
    if r.status == 200:
        ret = r.data.decode('unicode_escape')
        if ret == '1':
            headers = r.getheaders()
            print(headers["Set-Cookie"])
            cookies = headers["Set-Cookie"]
            cookie = cookies[:cookies.find(";")]
            # callback(cookie, assets)

            deploy_results = []
            for key in assets:
                    callback(cookie, key, deploy_results)
            
            if (len(deploy_results) > 0):
                print("deploy fail list:\n" + str(deploy_results))
                context["Status"] = "Fail"
                exit(0)

def upload(cookie, asset, results):
    print("cookie " + cookie)
    headers = {
        'Accept-Charset': 'utf-8',
        "Accept": "*/*",
        # 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
        # "Cookie":"adminid=111; reqenv=local; webenv=1; isAdmin=1; username=tcy; chinesename=%E5%94%90%E8%8D%89%E5%8E%9F; sidlist=%5B1%2C2%5D;"
    }
    headers["Cookie"] = "adminid=111; reqenv=local; webenv=1; isAdmin=1; username=tcy; chinesename=%E5%94%90%E8%8D%89%E5%8E%9F; sidlist=%5B1%2C2%5D; filemanager_dev=qcgh17qkkou75udf64f38q87qp;" + cookie
    
    webhook = "http://testadmin.superant.cc/config/syncBundleDir"
    http = urllib3.PoolManager()
    r = http.request(
        "POST",
        webhook,
        # /crazyfox/activity/Android/accumulated_pay/
        fields={"path":"/crazyfox/card/" + asset},
        headers=headers,
        timeout=3600)

    platform = ""
    if "Android" in asset:
        platform = "Android"
    else:
        platform = "iOS"
    ret = {"platform":platform, "activity":asset}
    if r.status == 200:
        resp = r.data.decode('unicode_escape')
        print(resp)
    else:
        results.append(ret)

def deploy(assets, context):
    login(upload, assets, context)